import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter_app_open_camera/base/base_container.dart';
import 'package:flutter_app_open_camera/page/main_page.dart';
import 'package:flutter_app_open_camera/utils/route_utils.dart';
import 'package:photo_view/photo_view.dart';

class TestImgPage extends StatelessWidget {
  final int index;

  final List<AlbumData> data;

  const TestImgPage({Key key, this.index, this.data}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BaseContainer(
      child: TestImg(
        index: index,
        data: data,
      ),
    );
  }
}

class TestImg extends StatefulWidget {
  final int index;

  final List<AlbumData> data;

  const TestImg({Key key, this.index, this.data}) : super(key: key);

  @override
  _TestImgState createState() => _TestImgState();
}

class _TestImgState extends State<TestImg>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  bool ready = false;
  FileImage fileImage;
  double scaleX = 1;

  void _updateImage(ImageInfo imageInfo, bool synchronousCall) {
    setState(() {
      ready = true;
    });
  }

  // ImageStream imageStream;
  // ImageStreamListener listener;
  int alpha = 255;
  double maxWidth = double.infinity;
  double currentWidth = double.infinity;

  AnimationController _container;
  PageController pageController;

  int index = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _container =
        AnimationController(duration: Duration(milliseconds: 300), vsync: this);
    index = widget.index;
    pageController = new PageController(initialPage: index);
    Future.delayed(Duration.zero, () {
      // pageController.jumpToPage(index);
      maxWidth = MediaQuery.of(context).size.width;
      currentWidth = MediaQuery.of(context).size.width;
      // fileImage = FileImage(widget.data[widget.index].file);
      // imageStream = fileImage.resolve(createLocalImageConfiguration(context));
      // listener = ImageStreamListener(_updateImage);
      // imageStream.addListener(listener);
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    // imageStream.removeListener(listener);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Color.fromARGB(alpha, 0, 0, 0),
      child: PageView(
        onPageChanged: (i) {
          index = i;
        },
        controller: pageController,
        children: getList(),
      ),
    );
  }

  Offset downOffset;
  double transformY = 0;
  double transformX = 0;
  double moveY = 0;
  double moveX = 0;
  bool animStart = false;

  List<Widget> getList() {
    List<Widget> widgetList = [];
    widget.data.forEach((element) {
      widgetList.add(_createItem(element));
    });
    return widgetList;
  }

  Widget _createItem(AlbumData element) {
    // FileImage fileImage = FileImage(element.file);
    // ImageStream imageStream =
    //     fileImage.resolve(createLocalImageConfiguration(context));
    // ImageStreamListener listener =
    //     ImageStreamListener((ImageInfo imageInfo, bool synchronousCall) {
    //   setState(() {
    //     element.ready = true;
    //   });
    // });
    // imageStream.addListener(listener);

    return GestureDetector(
      onTap: () {
        if (animStart) {
          return;
        }
        setState(() {});
        back(context);
      },
      onPanDown: (a) {
        if (animStart) {
          return;
        }
        downOffset = a.globalPosition;
      },
      onPanUpdate: (a) {
        if (animStart) {
          return;
        }
        double y = a.globalPosition.dy - downOffset.dy;
        double x = a.globalPosition.dx - downOffset.dx;
        transformY = y / 15;
        transformX = x;
        moveY = transformY;
        moveX = transformX;
        if (y >= 0) {
          alpha = 255 - y ~/ 15;
          if (alpha < 0) {
            alpha = 0;
          }
          currentWidth = maxWidth - y;

          if (currentWidth < maxWidth / 4) {
            currentWidth = maxWidth / 4;
          }
          setState(() {});
        }
        print('updateX--- $transformX  ');
      },
      onPanEnd: (a) {
        if (animStart) {
          return;
        }
        if (currentWidth <= maxWidth * 2 / 3) {
          setState(() {});
          back(context);
        } else {
          startAnim();
        }
      },
      child: Stack(
        alignment: Alignment.center,
        children: [
          Transform(
              transform: Matrix4.translationValues(0, transformY, 0),
              child: Hero(
                tag: index,
                child: FadeInImage(
                  width: double.infinity,
                  fadeInDuration: Duration(milliseconds:1),
                  fadeOutDuration: Duration(milliseconds: 1),
                  placeholder: MemoryImage(element.thumb),
                  image: FileImage(element.file),
                  fit: BoxFit.cover,
                ),
              ))
        ],
      ),
    );
  }

  Animation<double> animWidth;

  void startAnim() {
    _container.reset();
    animStart = true;
    double maxY = moveY;
    double maxX = moveX;
    double width = currentWidth;
    int maxAlpha = alpha;
    animWidth = CurveTween(curve: Curves.fastOutSlowIn).animate(_container);
    print('maxX --->$moveX   maxY ----> $transformX');
    animWidth.addListener(() {
      setState(() {
        transformY = maxY - maxY * animWidth.value;
        transformX = maxX - maxX * animWidth.value;
        print('moveX --->$transformX   moveY ----> $transformY');
        currentWidth = width + (maxWidth - width) * animWidth.value;
        alpha = (maxAlpha + (255 - maxAlpha) * animWidth.value).toInt();
      });
    });
    _container.forward();
    animWidth.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        animStart = false;
        moveY = 0;
        moveX = 0;
      }
    });
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
